﻿using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

namespace Iot.Shared.Helper;

public static class ThreadHelper
{
    /// <summary>
    /// </summary>
    /// <param name="task">执行任务</param>
    /// <param name="priority">线程等级</param>
    /// <param name="isBackground">是否为后台线程</param>
    /// <param name="message">错误提示</param>
    /// <param name="logger">日志类</param>
    public static void RunTask(this Func<Task> task, ThreadPriority priority = ThreadPriority.Normal,
        bool isBackground = false, string? message = null, ILogger? logger = null)
    {
        new Thread(() =>
        {
            try
            {
                task().GetAwaiter().GetResult();
            }
            catch (Exception e)
            {
                if (message is not null) logger?.LogError(e, "函数执行失败：{message}", message);
                else logger?.LogError(e, "函数执行失败");
            }
        })
        {
            IsBackground = isBackground,
            Priority = priority
        }.Start();
    }


    public static void Run(this Action action, ThreadPriority priority = ThreadPriority.Normal,
        bool isBackground = false, string? message = null, ILogger? logger = null)
    {
        new Thread(() =>
        {
            try
            {
                action();
            }
            catch (Exception e)
            {
                if (message is not null) logger?.LogError(e, "函数执行失败：{message}", message);
                else logger?.LogError(e, "函数执行失败");
            }
        })
        {
            IsBackground = isBackground,
            Priority = priority
        }.Start();
    }
}